package com.xinchen.all.ui.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContract
import androidx.annotation.RequiresApi
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.maple.base.base.BaseActivity
import com.maple.common.ui.activity.OcrActivity
import com.maple.model.data.BundleData
import com.maple.utils.const.ConstKey
import com.maple.utils.util.LogUtils
import com.maple.utils.util.PermissionUtils
import com.maple.utils.util.RequestPermissionResult
import com.maple.utils.util.UIUtils.Companion.parcelable
import com.maple.utils.util.UIUtils.Companion.serializable
import com.maple.utils.widget.update.XUpdateDownloader
import com.maple.utils.widget.update.XUpdateInstaller
import com.xinchen.all.R
import com.xinchen.all.app.MyApplication
import java.io.File

class PermissionActivity : BaseActivity() {

    private var tvResult: TextView? = null
    private var btnStorage: Button? = null
    private var btnBluetooth: Button? = null
    private var btnLocation: Button? = null
    private var btnOcr: Button? = null


    //声明AMapLocationClient类对象
    private var aMapLocationClient: AMapLocationClient? = null
    //声明定位回调监听器
    private val aMapLocationListener: AMapLocationListener = object : AMapLocationListener {
        override fun onLocationChanged(aMapLocation: AMapLocation?) {
            if(aMapLocation != null) {
                if (aMapLocation.errorCode == 0) {
                    LogUtils.logGGQ("===aMapLocation===>>${aMapLocation.address}")
                    LogUtils.logGGQ("===aMapLocation===>>${aMapLocation.latitude}")
                    LogUtils.logGGQ("===aMapLocation===>>${aMapLocation.longitude}")
                    val address: String = "纬度：${aMapLocation.latitude} - 经度：${aMapLocation.latitude} -地址：${aMapLocation.address}"
                    tvResult?.text = "位置：${address}"
                }
            }
        }
    }

    private val aMapLocationClientOption: AMapLocationClientOption by lazy {
        AMapLocationClientOption().apply {
//            this.locationPurpose = AMapLocationClientOption.AMapLocationPurpose.Sport
//            this.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
//            this.isOnceLocation = true
            this.isOnceLocationLatest = true
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_permission

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        tvResult = findViewById(R.id.tv_result)
        btnStorage = findViewById(R.id.btn_storage)
        btnBluetooth = findViewById(R.id.btn_bluetooth)
        btnLocation = findViewById(R.id.btn_location)
        btnOcr = findViewById(R.id.btn_ocr)
        btnStorage?.setOnClickListener {
            PermissionUtils.requestStorage(this, object :RequestPermissionResult{
                override fun onRequestPermissionSuccess() {
                    showToast("${btnStorage?.text} 申请通过")
                    tvResult?.text = "${btnStorage?.text} 申请通过"
                    downloadApk()
                }
            })
        }
        btnBluetooth?.setOnClickListener {
            PermissionUtils.requestBluetooth(this, object :RequestPermissionResult{
                override fun onRequestPermissionSuccess() {
                    showToast("${btnBluetooth?.text} 申请通过")
                    tvResult?.text = "${btnBluetooth?.text} 申请通过"
//                    onStartActivity(BluetoothActivity::class.java)
//                    onStartActivity(Bluetooth2Activity::class.java)
                    onStartActivity(BluetoothClassicActivity::class.java)
                }
            })
        }
        btnLocation?.setOnClickListener {
            PermissionUtils.requestLocation(this, object :RequestPermissionResult{
                override fun onRequestPermissionSuccess() {
                    showToast("${btnLocation?.text} 申请通过")
                    tvResult?.text = "${btnLocation?.text} 申请通过"
                    getLocation()
                }
            })
        }
        btnOcr?.setOnClickListener {
            launcherOcrResult.launch(BundleData(title = "Ocr扫码"))
        }
    }
    private val launcherOcrResult = registerForActivityResult(object :
        ActivityResultContract<BundleData, BundleData?>() {
        override fun createIntent(context: Context, input: BundleData): Intent {
            return Intent(this@PermissionActivity,OcrActivity::class.java).apply {
                putExtra(ConstKey.BundleKey.EXTRA_OBJ,input)
            }
        }

        override fun parseResult(resultCode: Int, intent: Intent?): BundleData? {
            if(intent != null) {
                return intent.parcelable(ConstKey.BundleKey.EXTRA_OBJ)
            }
            return null
        }
    }) {
        it?.let { data ->
            showToast(data.result)
        }
    }
    override fun initData(savedInstanceState: Bundle?) {
    }

    private fun getLocation() {
        AMapLocationClient.updatePrivacyAgree(applicationContext, true)
        AMapLocationClient.updatePrivacyShow(applicationContext, true, true)

        aMapLocationClient = AMapLocationClient(applicationContext)
        aMapLocationClient?.let {
            it.setLocationListener(aMapLocationListener)
            it.setLocationOption(aMapLocationClientOption)
        }
        aMapLocationClient?.startLocation()
    }


    private fun downloadApk() {
        val apkurl = "https://scsaas.oss-cn-shenzhen.aliyuncs.com/app/gufeiwulian/app_newest.apk"
        XUpdateDownloader().newBuild(this,apkurl,object :XUpdateDownloader.XUpdateDownloaderListener{
            override fun onStart() {
                LogUtils.logGGQ("onStart")
            }

            override fun onProgress(progress: Float?, total: Long?) {
                if(progress != null && total != null) {
                    LogUtils.logGGQ("onProgress:${Math.round(progress * 100)}")
                } else {
                    LogUtils.logGGQ("onProgress: null")
                }
            }

            override fun onCompleted(file: File?): Boolean {
                LogUtils.logGGQ("file:${file?.path}")
                if(file != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !this@PermissionActivity.packageManager.canRequestPackageInstalls()) {
                        launcherInstallResult.launch(file.path)
                    } else {
                        // 已经具有安装 APK 权限，可以进行安装操作
                        XUpdateInstaller().startInstallApk(this@PermissionActivity,file.path)
                    }

                    return true
                }
                return false
            }

            override fun onError(throwable: Throwable?) {
                LogUtils.logGGQ("onError:${throwable?.message}")
            }

        })
    }


    private val launcherInstallResult = registerForActivityResult(object :
        ActivityResultContract<String, String?>() {
        @RequiresApi(Build.VERSION_CODES.O)
        override fun createIntent(context: Context, input: String): Intent {
            val intent: Intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
            intent.data = Uri.parse("package:${MyApplication.instance.packageName}")
            intent.putExtra(ConstKey.BundleKey.EXTRA_URL,input)
            return intent
        }

        override fun parseResult(resultCode: Int, intent: Intent?): String? {
            return intent?.serializable(ConstKey.BundleKey.EXTRA_URL)
        }
    }) {
        if(!TextUtils.isEmpty(it)) {
            LogUtils.logGGQ("======安装=launcher=====>${it}")
            XUpdateInstaller().startInstallApk(this@PermissionActivity,it!!)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        aMapLocationClient?.let {
            it.unRegisterLocationListener(aMapLocationListener)
            it.stopLocation()
        }
    }
}